"""
date: 2018/8/14
function: 通过类来实现 search.py。
"""

class Search:
    count = 0
    """
    在函数中使用变量count需要声明global，在类中直接使用Search.count。
    """
    def __init__(self, path = '/usr/lib', dotname = '.py'):
        """
        :param path: 指定搜索的路径。
        :param dotname: 指定搜索的扩展名。
        """
        import os
        self.os = os
        self.path = path
        self.dotname = dotname

    def file(self, path):   # 比函数参数中少了type=.py。
        """
        function: 搜索到指定文件就计数。
        """
        if path[-len(self.dotname):] == self.dotname:
            Search.count += 1
            # for f in path:
            #     if f == ' find ':
            #         print(f)
        pass

    def dir(self, path):    # bi hanshu zhong shaole type canshu.
        """
        function: 使用递归搜索目录下不确定数量的目录。
        """
        paths = self.os.listdir(path)
        for p in paths:
            temp = self.combine(path, p)
            if self.os.path.isdir(temp):
                self.dir(temp)
            elif self.os.path.isfile(temp):
                print(temp)
                self.file(temp)
        pass

    def combine(self, path, sub):
        """
        function: 将指定路径和目录下的目录或文件进行合并成一个完成的路径。
        """
        return path + '/' + sub

    def main(self):
        """
        function: 主体.
        """
        if self.os.path.isdir(self.path):
            paths = self.os.listdir(self.path)
            for sub in paths:
                # print(sub)
                Search.count = 0                # 每次对新目录都对计数器归零。
                temp = self.combine(self.path, sub)
                if temp == '/usr/lib/llvm-4.0':
                    continue
                if self.os.path.isdir(temp):
                    self.dir(temp)
                    if Search.count > 0:
                        # print('%s dir sum : %d' % (temp, Search.count))
                        pass
                elif self.os.path.isfile(temp):
                    # print(temp)
                    pass
            pass
        else:
            print('you must set a dirctory')
        pass

"""
执行代码。
"""
class S(Search):
    pass

if __name__ == '__main__':
    s = S('/usr/lib/python2.7', '.h')
    s.main()
    pass